<template>
	<view class="banner">
		<el-card class="box-card">
			<div slot="header" class="clearfix">
				<span>APP轮播图管理</span>
				<el-button style="float: right;" icon="el-icon-plus" type="primary" :size="size" @click="addBanner">添加
				</el-button>
			</div>
			<view class="banner-list">
				<view class="b-l-li" v-for="(item,index) in bannerList" :key="index">
					<el-card :body-style="{ padding: '0px',height: '300px',position: 'relative'}">
						<image :src="item.fileId" class="image"></image>
						<view class="li-text">
							<view>APP点击此轮播图将会跳转到<el-link type="primary">【{{item.bookName}}】</el-link>小说的详情页面</view>
							<view class="bottom">
								<view>
									<el-tag type="success" :size="size">{{item.slot}}</el-tag>
								</view>
								<view>
									<el-link type="primary" @click="editBanner(item)">修改</el-link>
									<el-link type="danger" style="margin-left: 14px;" @click="delectBanner(item)">删除</el-link>
								</view>
							</view>
						</view>
					</el-card>
				</view>
				<el-empty description="暂无数据" v-if="bannerList.length==0" style="margin: auto;"></el-empty>
			</view>
		</el-card>

		<el-dialog title="轮播图管理" :visible.sync="dialog.show" v-dialogDrag>
			<view class="banner-form">
				<el-form :model="dialog.form" :rules="dialog.rules" ref="ruleForm" label-width="80px"
					class="demo-ruleForm" :size="size">
					<el-form-item label="轮播图" required>
						<fileUpload accept=".jpg,.jpeg,.png" @upload="uploadFile" ref="fileUpload" :limit="1">
						</fileUpload>
					</el-form-item>
					<el-form-item label="跳转小说" prop="bookName">
						<el-input class="el-input-230" v-model="dialog.form.bookName" :size="size" disabled></el-input>
						<el-button type="info" :size="size" style="margin-left: 10px;" @click="selectBokk">选取
						</el-button>
					</el-form-item>
					<el-form-item label="排序" prop="slot">
						<el-input-number class="el-input-230" v-model="dialog.form.slot" :min="1" :size="size"
							label="排序"></el-input-number>
					</el-form-item>
				</el-form>
			</view>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialog.show = false" :size="size">取 消</el-button>
				<el-button type="primary" @click="submit" :size="size" :loading="dialog.loading">提 交</el-button>
			</span>
		</el-dialog>

		<book-list :show="bookList.show" @submit="getsubmit" @cancel="cancel"></book-list>

	</view>
</template>

<script>
	let that
	import {
		mapState
	} from 'vuex'
	export default {
		computed: {
			...mapState('ui', ['size'])
		},
		data() {
			return {
				dialog: {
					type:'add',//当前是编辑还是修改
					loading: false,
					show: false,
					form: {
						fileId: '', //已上传的图片
						bookName: '', //已选择的小说名称
						bookId: '', //已选择的小说id 
						slot: 1, //轮播图排序
					},
					rules: {
						bookName: [{
							required: true,
							message: '跳转小说必填',
							trigger: 'change'
						}],
						slot: [{
							required: true,
							message: '排序必填',
							trigger: 'change'
						}],
					}
				},
				bookList: {
					show: false,
					selectItem: '' //已选择的小说
				},
				bannerList:[],//轮播图列表

			}
		},
		onReady() {
			that = this
			//获取轮播图列表
			that.getBannerList()
		},
		methods: {
			//修改轮播图
			editBanner(item){
				console.log(item);
				this.dialog.type='edit'
				this.dialog.show=true
				this.dialog.form={...item}
				this.$nextTick(function(){
					let data={
						uid:item._id,
						url:item.fileId
					}
					that.$refs.fileUpload.setFileList([data])
				})
			},
			//删除轮播图
			delectBanner(item){
				uni.showModal({
					title: '提示',
					content: '是否确认此操作？',
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if(res.confirm){
							let req = {
								params: {
									bannerId:item._id,
									fileId:item.fileId
								},
								active: 'delectBanner',
								showLoad: true
							}
							uni.$lizhao.doCloud('banner-cloud', req).then(res => {
								console.log(res);
								if (res.code == 0) {
									//获取轮播图列表
									that.getBannerList()
								}
							})
						}
					},
				});
			},
			//获取轮播图列表
			getBannerList() {
				let req = {
					active: 'getBannerList',
					showLoad: true
				}
				uni.$lizhao.doCloud('banner-cloud', req).then(res => {
					console.log(res.data);
					if (res.code == 0) {
						that.bannerList=res.data
					}
				})
			},
			//点击确认选取小说
			getsubmit(data) {
				that.bookList.show = false
				that.bookList.selectItem = JSON.parse(data)
				that.dialog.form.bookName = that.bookList.selectItem.bookName
				that.dialog.form.bookId = that.bookList.selectItem._id
			},
			//选择小说
			selectBokk() {
				that.bookList.show = true
			},
			//取消选择
			cancel(){
				that.bookList.show = false
			},
			//提交校验
			submit() {
				if (!that.dialog.form.fileId) {
					this.$message.warning('轮播图必填项')
					return
				}
				this.$refs.ruleForm.validate((valid) => {
					if (valid) {
						if(that.dialog.type=='add'){
							that.addBannerFn()
						}else{
							console.log(that.dialog.form);
							that.editBannerFn()
						}
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			//修改轮播图数据
			editBannerFn(){
				that.dialog.loading = true
				let req = {
					params: that.dialog.form,
					active: 'editBanner',
					showLoad: false
				}
				uni.$lizhao.doCloud('banner-cloud', req).then(res => {
					console.log(res);
					if (res.code == 0) {
						this.$message.success('修改成功')
						//标记下当前图片id被使用了
						that.waiterfile(that.dialog.form.fileId, 'update')
						that.dialog.show = false
						//获取轮播图列表
						that.getBannerList()
					}
					that.dialog.loading = false
				})
			},
			//添加轮播图数据
			addBannerFn() {
				that.dialog.loading = true
				let req = {
					params: that.dialog.form,
					active: 'addBanner',
					showLoad: false
				}
				uni.$lizhao.doCloud('banner-cloud', req).then(res => {
					if (res.code == 0) {
						this.$message.success('添加成功')
						//标记下当前图片id被使用了
						that.waiterfile(that.dialog.form.fileId, 'update')
						that.dialog.show = false
						//获取轮播图列表
						that.getBannerList()
					}
					that.dialog.loading = false
				})
			},
			//上传
			async uploadFile(data) {
				const result = await uniCloud.uploadFile({
					filePath: data.file.url,
					cloudPath: data.file.name,
					onUploadProgress: function(progressEvent) {
						var percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent
							.total);
						that.$refs.fileUpload.setProgress(percentCompleted, true)
					}
				});
				that.$refs.fileUpload.setProgress(0, false)
				if (result.success) {
					data.file.url = result.fileID
					that.dialog.form.fileId = result.fileID
					that.$refs.fileUpload.setFileList([data.file])
					//上传成功后把资源写到数据库，防止重复上传（后面可以把未使用的图片从云存储中删除）
					that.waiterfile(result.fileID, 'add')
				} else {
					that.$refs.fileUpload.setFileList([])
				}
			},
			// 上传成功后把资源写到数据库，防止重复上传（后面可以把未使用的图片从云存储中删除）
			//type为add添加数据，update更新
			waiterfile(fileId, type) {
				let req = {
					params: {
						type,
						fileId,
					},
					active: 'uploadFile',
					showLoad: false
				}
				uni.$lizhao.doCloud('filelist-cloud', req).then(res => {
					if (type == 'update' && res.code == 0) {
						//更新成功后，把之前上传的无用的图片从数据库和云存储中删除，防止资源浪费
						that.delectFile()
					}
				})
			},
			//提交成功后，把之前上传的无用的图片从数据库和云存储中删除，防止资源浪费
			delectFile() {
				let req = {
					active: 'delectFile',
					showLoad: false
				}
				uni.$lizhao.doCloud('filelist-cloud', req).then(res => {
					console.log(res);
				})
			},
			addBanner() {
				this.dialog.show = true
				that.bookList.show = false
				this.dialog.type='add'
				//重置表单
				this.dialog.form={
					fileId: '', //已上传的图片
					bookName: '', //已选择的小说名称
					bookId: '', //已选择的小说id 
					slot: 1, //轮播图排序
				}
				this.$nextTick(function(){
					that.$refs.fileUpload.setFileList([])
				})
			}
		}
	}
</script>
<style lang="scss" scoped>
	.banner-list {
		display: flex;
		flex-wrap: wrap;
		.b-l-li{
			margin-bottom: 10px;margin-right: 10px;width: 300px;
			.image{
				width: 100%;height: 120px;
			}
			.li-text{
				padding: 14px;
				.bottom{
					display: flex;justify-content: space-between;width: 90%; position: absolute;bottom: 14px;right:14px;
				}
			}
		}
	}
</style>
